var Index = function () {
    return {
        //main function to initiate the module
        init: function () {
            var _this = this;
//          App.addResponsiveHandler(function () {
//              Index.initCalendar();
//              jQuery('.vmaps').each(function () {
//                  var map = jQuery(this);
//                  map.width(map.parent().width());
//              });
//          });
            var _menuMsg = JSON.parse(localStorage.getItem("menuMsg"));
            this.permissionMenuOption();//权限配置菜单

//			this.getMenu();//获取菜单信息(模拟数据)
            //延时处理
            setTimeout(function () {
                _this.initLoad();
            }, 500);

            this.menuEvent();//菜单事件
            this.getUserMsgs();//用户信息
            this.getStyle_color();//皮肤样式
            this.changePwd();//密码修改
            this.changePwdFn();
            this.logout();//用户退出

//          if (_.has(_menuMsg, "4")) {//有预警管理权限（预警管理的id为4）
//              this.warningPush();//获取预警信息
//              this.warningOption();//预警信息操作
//          }
//          else {
//              $("#header_notification_bar").hide();
//          }
            //判断是否有预警管理的权限，
             $("#header_notification_bar").hide();
             for(var key in _menuMsg){
             	if(_menuMsg[key].name == "预警管理"){
             		$("#header_notification_bar").show();
             		this.warningPush();//获取预警信息
              		this.warningOption();//预警信息操作
             	}
             	if(_menuMsg[key].name == "工作台"){
             		$("#iframe").attr("src","component/dashboard/dashboard_2.0.html");
             		$(".breadcrumbLi.second").find("a").text("工作台");
             		$(".breadcrumbLi.second").find("i").removeClass("hide");
             		$(".breadcrumbLi.third").find("a").text("工作台统计").removeClass("hide");
             	}
             }

        },
        initCalendar: function () {
            if (!jQuery().fullCalendar) {
                return;
            }

            var date = new Date();
            var d = date.getDate();
            var m = date.getMonth();
            var y = date.getFullYear();

            var h = {};

            if ($('#calendar').width() <= 400) {
                $('#calendar').addClass("mobile");
                h = {
                    left: 'title, prev, next',
                    center: '',
                    right: 'today,month,agendaWeek,agendaDay'
                };
            } else {
                $('#calendar').removeClass("mobile");
                if (App.isRTL()) {
                    h = {
                        right: 'title',
                        center: '',
                        left: 'prev,next,today,month,agendaWeek,agendaDay'
                    };
                } else {
                    h = {
                        left: 'title',
                        center: '',
                        right: 'prev,next,today,month,agendaWeek,agendaDay'
                    };
                }
            }

            $('#calendar').fullCalendar('destroy'); // destroy the calendar
            $('#calendar').fullCalendar({ //re-initialize the calendar
                disableDragging: false,
                header: h,
                editable: true,
                events: [{
                    title: 'All Day Event',
                    start: new Date(y, m, 1),
                    backgroundColor: App.getLayoutColorCode('yellow')
                }, {
                    title: 'Long Event',
                    start: new Date(y, m, d - 5),
                    end: new Date(y, m, d - 2),
                    backgroundColor: App.getLayoutColorCode('green')
                }, {
                    title: 'Repeating Event',
                    start: new Date(y, m, d - 3, 16, 0),
                    allDay: false,
                    backgroundColor: App.getLayoutColorCode('red')
                }, {
                    title: 'Repeating Event',
                    start: new Date(y, m, d + 4, 16, 0),
                    allDay: false,
                    backgroundColor: App.getLayoutColorCode('green')
                }, {
                    title: 'Meeting',
                    start: new Date(y, m, d, 10, 30),
                    allDay: false,
                }, {
                    title: 'Lunch',
                    start: new Date(y, m, d, 12, 0),
                    end: new Date(y, m, d, 14, 0),
                    backgroundColor: App.getLayoutColorCode('grey'),
                    allDay: false,
                }, {
                    title: 'Birthday Party',
                    start: new Date(y, m, d + 1, 19, 0),
                    end: new Date(y, m, d + 1, 22, 30),
                    backgroundColor: App.getLayoutColorCode('purple'),
                    allDay: false,
                }, {
                    title: 'Click for Google',
                    start: new Date(y, m, 28),
                    end: new Date(y, m, 29),
                    backgroundColor: App.getLayoutColorCode('yellow'),
                    url: 'http://google.com/',
                }
                ]
            });
        },
        //缓存历史菜单
        initLoad: function () {
            var lis = $(".page-sidebar-menu").children(".lis");
            var f = lis.children("a");
            var c = lis.children(".sub-menu").children("li").children("a");
            var ele = [f, c];
            var reload = {
                title: "", // title is a key ,
                titleVal: [],
                init: function () {
                    this.title = encodeURI($("title").text());
                    this.addId(); // 添加id
                    this.pageRestore(); // 页面还原
                },
                addId: function () {
                    var _this = this;
                    for (var i = 0; i < ele.length; i++) {
                        $(ele[i]).each(function (j, k) {

                            $(k).attr("data-id", String(i) + j)
                            .attr("data-i", i)
                            .on("click", function (e) {
                                _this.clickMonitoring($(this));
                            });
                        });
                    }
                },
                pageRestore: function () {
                    var val = sessionStorage.getItem(this.title);
                    if (val) {
                        val = val.indexOf(",") ? val.split(",") : new Array(val);
                        for (var i = 0; i < val.length; i++) {
                            $.each(ele[i], function (j, k) {
                                var id = $(k).attr("data-id");
                                if (id == val[i]) {
                                    $(k).trigger("click");
                                }
                            });
                        }
                    }
                },
                clickMonitoring: function (that) {
                    var index = that.attr("data-i");
                    this.titleVal[index] = that.attr("data-id");
                    sessionStorage.setItem(this.title, this.titleVal);
                    /** [可选优化] 有一种情况: 没点父元素,直接点击子元素,则之前存的父元素就不对了
                     *  可以用 (子元素).parent() 方法往上找, 直到data-id 以0开头为止.*/
                }
            };
            reload.init();

        },
        //获取菜单数据
        getMenu: function () {
            //获取菜单
            $.ajax({
                type: "get",
                url: "json/menu.json",
                async: true,
                success: function (data) {
                    console.log(data);
                    $(".page-sidebar-menu").find(".lis").remove();
                    $.each(data.data, function (i, v) {
                        var lis = '<li class="lis " data-id="' + v.id + '">' +
                            '<a data-href="javascript:void(0);">' +
                            '<i class="' + v.icon + '"></i>' +
                            '<span class="title">' + v.name + '</span>' +
                            '<span class="arrow "></span>' +
                            '</a>' +
                            '<ul class="sub-menu">' +
                            createSecondLi(v.list) +
                            '</ul>' +
                            '</li>';
                        $(".page-sidebar-menu").append($(lis));
                    });
                }
            });

            //返回active和open状态
//			function backActive
            /*
             渲染二级菜单
             * @param list 二级菜单数组
             * @return {string}
             * */
            function createSecondLi(list) {
                if (list.length > 0) {
                    var lis = "";
                    $.each(list, function (i, v) {
                        lis += '<li class="' + backHide(v.show) + '" data-mainid="' + v.id + '" data-mainpid="' + v.pid + '">' +
                            '<a data-href="' + v.url + '">' +
                            v.name +
                            '</a>' +
                            '</li>';
                    });
                    return lis;
                }

            }

            //返回显示隐藏类名
            function backHide(nShow) {
                if (nShow == 0) {
                    return "";
                } else {
                    return "hide";
                }
            }
        },
        //监听菜单点击切换iframe事件
        menuEvent: function () {
            resetHeight();
            //菜单路由

            $("body").on('click', '.page-sidebar-menu>li>a', function (event) {
                var sub = $(this).next();

                // 可见
                if (sub.is(":visible")) {
                    $(".arrow").removeClass("open");
                    sub.slideUp(200);
                } else {
                    $(".arrow").removeClass("open");
                    $(this).children(".arrow").addClass("open"); // 展开箭头

                    // 添加背景
                    var parentLi = jQuery(this).parent();
                    parentLi.siblings().children(".sub-menu:visible").slideUp();

                    // 展开菜单动画
                    sub.slideDown();
                }

                resetHeight();
                $(".homeLi").nextAll(".breadcrumbLi").remove();
                var sTitle = $(this).children(".title").text();
                var sLi = '<li class="breadcrumbLi">' +
                    '<a href="#">' + sTitle + '</a>' +
                    '</li>';
                $(".homeLi").after($(sLi));
                $(".page-title").html(sTitle);

                $(this).parent('li').addClass("active").siblings("li").removeClass("active");
                $(this).parent('li').siblings("li").find("li").removeClass("active");
                event.preventDefault();
            });


            $("body").on('click', '.page-sidebar-menu .sub-menu>li a', function (event) {
                $(this).parent().addClass("active").siblings("li").removeClass("active");
                $("iframe").attr('src', $(this).attr("data-href"));
                resetHeight();
                $(".homeLi").nextAll(".breadcrumbLi").remove();
                var cTitle = $(this).text();
                var pTitle = $(this).parents("ul").prev("a").children(".title").text();
                var sLis = '<li class="breadcrumbLi">' +
                    '<a href="#">' + pTitle + '</a>' +
                    '<i class="icon-angle-right"></i>' +
                    '</li>' +
                    '<li class="breadcrumbLi">' +
                    '<a href="#">' + cTitle + '</a>' +
                    '</li>';
                $(".homeLi").after($(sLis));
                $(".page-title").html(cTitle);
                event.preventDefault();
                event.stopPropagation();
            });

            //自动计算高度
            function resetHeight() {
                var nH_row_fluid = $('.row-fluid').height();
                var nH_header = $(".header").height();
                var nH_html = $("html").height();
                var nH_iframe = nH_html - nH_row_fluid - nH_header;
                $("iframe").css("height", nH_iframe + "px");
            }
        },
        //获取登录用户的所有信息,和相关信息，并且渲染
        getUserMsgs: function () {
            //初始化logo
            if (localStorage.getItem("schoolLogo")) {
                $(".brand img").attr({
                    "src": localStorage.getItem("schoolLogo")
                }).css({
                    "width": "auto",
                    "height": "100%"
                })
            }

            var userMsg = JSON.parse(localStorage.getItem("userMsg"));//存用户信息
//			var roleMsg = JSON.parse(localStorage.getItem("roleMsg"));//存用户角色信息
//			var layoutMsg = JSON.parse(localStorage.getItem("layoutMsg"));//存用户个性化定制数据
            //初始化用户信息
            $(".username").text(userMsg.username);
            //初始化学校名称
            $(".schoolName").text(localStorage.getItem("schoolName"));
			$("title").text(localStorage.getItem("schoolName") + "考勤系统");
            //加载时间
            function loadTime() {
                $(".timeBox a").text($.getOnTime("ZW"));
                setTimeout(loadTime, 1000);
            }

            loadTime();

        },
        //获取皮肤样式
        getStyle_color: function () {
            console.log($.cookie('style_color'));
            if ($.cookie('style_color'))
                $("#style_color").attr("href", "css/" + $.cookie('style_color') + ".css");
        },
        //修改个人密码入口模态框
        changePwd: function () {
            $(".btn-change-pwd").on("click", function () {
                $("#changePwdBox").modal("toggle");
            });
        },
        //实例化密码修改正则规则
        changePwdFn: function () {
            //初始化表单验证
            $('#changePwdForm')
            .bootstrapValidator({
                message: '这个值是无效的',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    old_pwd: {
                        validators: {
                            notEmpty: {
                                message: '<b style="color:red;">旧密码是必需的，不能是空的</b>'
                            },
                            stringLength: {
                                min: 6,
                                max: 20,
                                message: '<b style="color:red;">旧密码必须大于6，小于20个字符</b>'
                            },
                            regexp: {
                                regexp: /^[a-zA-Z0-9_\.]+$/,
                                message: '<b style="color:red;">旧密码只能由字母、数字、点和下划线组成</b>'
                            },
                            different: {
                                field: 'password',
                                message: '<b style="color:red;">旧密码不可能与新密码相同</b>'
                            }
                        }
                    },
                    password: {
                        validators: {
                            notEmpty: {
                                message: '<b style="color:red;">新密码是必需的，不能是空的</b>'
                            },
                            stringLength: {
                                min: 6,
                                max: 20,
                                message: '<b style="color:red;">新密码必须大于6，小于20个字符</b>'
                            },
                            regexp: {
                                regexp: /^[a-zA-Z0-9_\.]+$/,
                                message: '<b style="color:red;">新密码只能由字母、数字、点和下划线组成</b>'
                            },
                            different: {
                                field: 'old_pwd',
                                message: '<b style="color:red;">新密码不可能与旧密码相同</b>'
                            }
                        }
                    },
                    confirmPassword: {
                        validators: {
                            notEmpty: {
                                message: '<b style="color:red;">确认新密码是必需的，不能是空的</b>'
                            },
                            identical: {
                                field: 'password',
                                message: '<b style="color:red;">新密码和它的确认是不一样的</b>'
                            },
                            different: {
                                field: 'username',
                                message: '<b style="color:red;">新密码不可能与用户名相同</b>'
                            }
                        }
                    },

                }
            })
            .on('success.form.bv', function (e) {
                // 阻止表单提交
                e.preventDefault();
                // 获得表单实例
                var $form = $(e.target);
                fnAjax.method_4(
                    url_join("free/changepassword"),
                    $.serializeToObj($form.serialize()),
                    "post",
                    function (data) {
                        console.log(data);
                        layer.msg("操作成功", {
                            time: 1500
                        }, function () {
                            $("#changePwdBox").modal("toggle");
                        });
                    }
                );
            });
            // 手动验证表单
            $('.btn-save-pwd').click(function () {
                $('#changePwdForm').bootstrapValidator('validate');
            });
        },
        //退出
        logout: function () {
            $(".exitBtn").on("click", function () {
                fnAjax.method_4(
                    url_join("free/userlogout"),
                    {},
                    "post",
                    function () {
                    	sessionStorage.clear();
                        layer.msg("操作成功", {time: 1000}, function () {
//                          window.location.href = "login.html";
							$.toNewPage($.getLoginUrl());
                        });
                    }
                );
            });
        },
        //预警信息
        warningPush: function () {
            getWarningMsg();
            var warningTimer = setInterval(getWarningMsg, 1000 * 60 * 1);

            //获取预警信息
            function getWarningMsg() {
                //自动生成未读数据，测试用
//				fnAjax.method_4(
//					url_join("warning/init"),
//					{},
//					"post",
//					function(data){
//						
//					}
//				);

                //获取需要推送的预警信息
                fnAjax.method_4(
                    url_join("warning/send"),
                    {},
                    "post",
                    function (data) {
                        $('#header_notification_bar').pulsate("destroy");
                        console.log(data);                        
                        if (data.data.length > 0) {
                            createList(data.data, $(".notification"));
                        }

                    }
                );
            }

            /**
             渲染list
             @param {Array} aData 预警信息数据
             @param {Object} container 列表容器jq对象
             @prop {Number} id 某条预警信息的id
             @prop {String} content 某条预警信息的内容
             @prop {String} time 某条预警信息标示的时间
             * */
            function createList(aData, container) {
                $('#header_notification_bar').pulsate({
                    color: "#bf1c56",
                }).on("click", function () {
                    $(this).pulsate("destroy").unbind("click");
                });
                $(".warninCount").text(aData.length);
                container.find(".msg-li").remove();
                var lis = "";
                $.each(aData, function (i, v) {
                    lis += '<li class="msg-li" data-id="' + v.id + '">' +
                        '<a href="javascript:;" class="parentClear">' +
                        '<span class="label label-info">' +
                        '<i class="icon-bullhorn"></i>' +
                        '</span>' +
                        '<i>' + v.username + v.message + '</i>' +
                        //	                                   	'<span class="time rf">'+ v.time +'</span>'+
                        '</a>' +
                        '</li>';
                });
                container.children("li:first-child").after($(lis));
            }
        },
        //预警信息操作
        warningOption: function () {
            var aW = [];
            $(".msg-li").each(function () {
                aW.push($(this).attr("data-id"));
            });
            //一次性清空预警信息（已阅）
            $(".external").on("click", function () {
                fnAjax.method_4(
                    url_join("warning/read"),
                    {warnings: aW},
                    "post",
                    function (data) {
                        console.log(data);
                        $(".external").siblings(".msg-li").remove();
                        $(".warninCount").text(0);
                    }
                );

            });
            //单条阅读
            $("body").on("click", ".msg-li", function () {
                fnAjax.method_4(
                    url_join("warning/read"),
                    {warnings: [$(this).attr("data-id")]},
                    "post",
                    function (data) {
                        console.log(data);
                        $(this).remove();
                        $(".warninCount").each(function () {
                            var n = $(this).text() * 1;
                            $(this).text(n - 1);
                        });
                    }
                );

            });
        },
        //权限菜单配置
        permissionMenuOption: function () {
            var aMenu = [];
            if (localStorage.getItem("menuMsg")) {
                var menuMsg = JSON.parse(localStorage.getItem("menuMsg"));                                
                if(menuMsg.length > 0){
                	for (var k in menuMsg) {
	                    aMenu.push(menuMsg[k]);
	                }
	                //渲染菜单导航
	                $(".page-sidebar-menu").find(".lis").remove();
	                $.each(aMenu, function (i, v) {
	                    var lis = '<li class="lis" data-id="' + v.id + '">' +
	                        '<a data-href="javascript:void(0);">' +
	                        '<i class="' + v.icon_name + '"></i>' +
	                        '<span class="title">' + v.name + '</span>' +
	                        '<span class="arrow "></span>' +
	                        '</a>' +
	                        '<ul class="sub-menu">' +
	                        createSecondLi(v.children) +
	                        '</ul>' +
	                        '</li>';
	                    $(".page-sidebar-menu").append($(lis));
	                    console.log(v.children);
	                });
                }
                else{
                	//普通用户，（没有操作权限，只有公共权限的人）
//              	$(".page-container,.sidebar-toggler.hidden-phone").hide();
//              	layer.alert("该账户为普通用户，没有系统权限！")
                }

            } else {
                layer.alert("权限菜单参数出错，请重新登录");
            }
            //返回active和open状态
//			function backActive
            /**
             渲染二级菜单
             * @param list 二级菜单数组
             * @return {string}
             * */
            function createSecondLi(list) {
                console.log(list);
                if (list.length > 0) {
                    var lis = "";
                    $.each(list, function (i, v) {
                        lis += '<li class="" data-mainid="' + v.id + '" data-mainpid="' + v.menu_id + '">' +
                            '<a data-href="' + v.url + '">' +
                            v.name +
                            '</a>' +
                            '</li>';
                    });
                    return lis;
                }

            }
        },
        
        ///
    };
}();